package kr.co.casually.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import kr.co.casually.ImageLoader;
import kr.co.casually.R;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.preference.PreferenceManager;

public class Utils {

	public static final String LOG_TAG = "FacebookCon";
	public static boolean D = true;
	public static final String FACEBOOK_APP_ID = "197728696963047";
	public static final int FACEBOOK_AUTH_CODE = 32665;

	public static final int REQ_CODE_FACEBOOK = 123;
	public static final int REQ_CODE_TWITTER = 456;
	public static final int REQ_CODE_ME2DAY = 789;

	public static final String NAMESPACE = "http://service.art.culture.openapi.ubizvalley.com";
	public static final String URL = "http://mobile.openapi.seoul.go.kr/SeoulOpenAPI/services/ArtService?wsdl";
	public static final String DIALOG_MSG = "잠시만 기다려 주세요";

	public static int CREATE_DB_INCREMENT = 0;

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	public static String encodeBinary(byte[] src) {
		try {
			return new String(Base64.encodeBase64(src));
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getGenreName(Context context, int genrePosition) {

		String[] genreName; // 장르명
		Resources res = context.getResources();
		genreName = res.getStringArray(R.array.genre_name);
		return genreName[genrePosition];

	}

	public static int getGenreCode(Context context, int genrePosition) {

		int[] genreCode; // 장르명
		Resources res = context.getResources();
		genreCode = res.getIntArray(R.array.genre_code);
		return genreCode[genrePosition];

	}

	// 설정 알림 설정여부
	public static boolean getPreferenceNotiMsg(Context context) {

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		return prefs.getBoolean("noti_preference", false);
	}

	// 설정 사운드 설정여부

	public static boolean getPreferenceNotiSound(Context context) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		return prefs.getBoolean("noti_sound_preference", false);
	}

	// 설정 진동 설정여부
	public static boolean getPreferenceNotiVibrate(Context context) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		return prefs.getBoolean("noti_vibration_preference", false);
	}

	// 설정 시간 설정여부
	public static boolean getPreferenceTImeSet(Context context) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		return prefs.getBoolean("time_preference", false);
	}

	// 설정 오전오후 가져오기(0,1)
	public static String getPreferenceTImeSetAmPm(Context context) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		return prefs.getString("ampm_list_preference", "0");
	}

	// 설정 시간가져오기
	public static String getPreferenceTImeSetHour(Context context) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		return prefs.getString("hour_list_preference", "1");
	}

	// 현재 화면이 Act_Talk Activity 인경우
	private boolean foregroundAct(Context context, String className) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
		ComponentName topActivity = taskInfo.get(0).topActivity;
		String str = topActivity.getClassName();
		return (str.equals(className)) ? true : false;
	}

	// 오늘 새벽 4시 시간 가져 오기
	public static long getTodayAlarmTime() {
		Date today = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.set(today.getYear(), today.getMonth(), today.getDate());
		calendar.set(Calendar.AM_PM, Calendar.PM);
		calendar.set(Calendar.HOUR_OF_DAY, 9);
		calendar.set(Calendar.MINUTE, 7);
		calendar.set(Calendar.SECOND, 0);

		return calendar.getTimeInMillis();
	}

	public static long getNotificationTime(int ampm, int hour) {
		Date today = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.set(today.getYear(), today.getMonth(), today.getDate());
		calendar.set(Calendar.AM_PM, ampm);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);

		return calendar.getTimeInMillis();
	}

	// 객체 null검사
	public static String ifNull(Object str) {
		String retStr = "";
		if (str == null) {
			retStr = "";
		} else if (str.toString().contains("anyType")) {
			retStr = "";
		} else {
			retStr = str.toString();
		}
		return retStr;

	}

	/**
	 * 공백 또는 null인지 검사
	 */
	public static boolean isEmpty(String str) {
		if (str == null)
			return true;
		if (str.equals(""))
			return true;
		if (str.trim().length() == 0)
			return true;

		return false;
	}

	/**
	 * 특수문자 변환 된것을 원형으로 돌림
	 */
	public static String changeToHtml(String param) {
		String str = "";
		try {
			param = param.replaceAll("&amp;", "&");
			param = param.replaceAll("&lt;", "<");
			param = param.replaceAll("&gt;", ">");
			param = param.replaceAll("&quot;", "\"");
			param = param.replaceAll("&#39;", "\'");
			param = param.replaceAll("![*][*]!", "\"");

			str = param;
		} catch (Exception e) {
			str = "";
		}

		return str;
	}

	// Post 방식 결과값 반환
	public String getReturnResult(String url, NameValuePair... nameValuePairs) {
		String returnResult = null;
		HttpUtil hu = new HttpUtil(HttpUtil.createHttpClient(), null);
		try {
			returnResult = hu.doHttpPost(url, nameValuePairs);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return returnResult;
	}

	// Get 방식 결과값 반환
	public String getReturnResultGet(String url,
			NameValuePair... nameValuePairs) {
		String returnResult = null;
		HttpUtil hu = new HttpUtil(HttpUtil.createHttpClient(), null);
		try {
			returnResult = hu.doHttpGet(url, nameValuePairs);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return returnResult;
	}

	// 앱 종료 다이얼로그
	public static Dialog getAppCloseDialog(final Activity act) {

		return new AlertDialog.Builder(act)
				.setIcon(R.drawable.icon)
				.setTitle(R.string.alert_dialog_app_close_title)
				.setNegativeButton(R.string.cancel_kr,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {

							}
						})
				.setPositiveButton(R.string.ok_kr,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								act.finish();
								ImageLoader imageLoader = new ImageLoader(act);
								imageLoader.clearCache();
							}
						}).create();
	}
}